package com.loozb.daemon;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.stream.IntStream;

/**
 * 守护线程  批量保存日志
 */
public class Main {

    private Queue<SysLog> queue = new LinkedBlockingDeque<>();

    private DaemonThread daemonThread = null;

    public boolean add(SysLog sysLog) {
        if(daemonThread == null) {
            createDaemonThread();
        }
        return queue.add(sysLog);
    }

    private synchronized void createDaemonThread() {
        if(daemonThread == null) {
            daemonThread = new DaemonThread();
        }
    }

    public class DaemonThread extends Thread {
        public DaemonThread() {
            this.setDaemon(true);
            this.setName("收集日志守护线程");
            this.start();
        }
        @Override
        public void run() {
            while (true) {
                try {
                    int size = queue.size();
                    System.out.println("线程获取到条数：" + size);
                    if(size == 0) {
                        Thread.sleep(2000);
                        continue;
                    }
                    List<SysLog> sysLogList = new ArrayList<>();
                    int num = size > 5 ? 5 : size;
                    for(int i = 0; i < num; i++) {
                        SysLog sysLog = queue.poll();
                        if(sysLog != null) {
                            sysLogList.add(sysLog);
                        }
                    }
                    if(!sysLogList.isEmpty()) {
                        //批量保存
                        System.out.println("批量保存日志条数:" + sysLogList.size());
                    }
                }  catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Main m = new Main();
        SysLog sysLog = null;
        for(int i = 0; i < 1000; i++) {
            sysLog = new SysLog();
            sysLog.setIdx(i + "");
            m.add(sysLog);
        }
    }
}
